from flask_restplus import Resource, Namespace, fields, marshal, reqparse, Model
from common.decorators import catch_error
from app.product.unit import service
from app.user.decorators import token_required
from common.responses import ok
from flask import g
from common.response_model import base_model, pagination_model
from common.request_parser import get_parser as base_get_parser
from app.product.unit.model import Unit
from app.product.unit import dao

api = Namespace('unit')

# ---------- model ----------
unit_model = base_model.inherit('unit_model', {
    "show_order": fields.Integer(description='显示顺序'),
})
unit_paginate_model = pagination_model.inherit('unit_paginate_model', {
    "items": fields.Nested(unit_model)
})
# ---------- create parser ----------
create_parser = reqparse.RequestParser()
create_parser.add_argument('name', type=str, help='单位名称')
create_parser.add_argument('notes', type=str, help='备注')
create_parser.add_argument('show_order', type=str, help='显示顺序')
create_parser.add_argument('is_active', type=bool, choices=[True, False], help='是否启用')
# ---------- get parser ----------
get_parser = base_get_parser.copy()
get_parser.replace_argument('order_by', dest='sorted_by', type=str, choices=[
    'name', 'id', 'show_order'
], default='show_order', help='sorted_by')
get_parser.add_argument('filter_ids', type=int, help='过滤ids', action='append')


class UnitsResource(Resource):
    @catch_error
    @token_required
    @api.expect(create_parser)
    def post(self):
        args = create_parser.parse_args()
        new_obj = Unit.create(**args, commit=True)
        return ok(data=marshal(new_obj, unit_model),
                  message='create success')

    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()
        print('args', args)
        pagination = dao.get_by_page(**args)
        return ok(data=marshal(pagination, unit_paginate_model),
                  message='get success')


# ---------- put parser ----------
put_parser = create_parser.copy()


class UnitResource(Resource):
    @catch_error
    @token_required
    def get(self, obj_id):
        """获取"""
        obj = Unit.query.filter_by(id=obj_id).first()
        return ok(data=marshal(obj, unit_model),
                  message='get success')

    @catch_error
    @token_required
    @api.expect(put_parser)
    def put(self, obj_id):
        """更新"""
        args = put_parser.parse_args()

        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]
        obj = Unit.query.filter_by(id=obj_id).first()
        obj.update(**args, commit=True)
        return ok(data=marshal(obj, unit_model),
                  message='update success')

    @catch_error
    @token_required
    def delete(self, obj_id):
        """删除"""
        obj = Unit.query.filter_by(id=obj_id).first()
        delete_id = obj.hard_delete(commit=True)
        return ok(
            data={
                'id': delete_id
            },
            message='delete success')


api.add_resource(UnitsResource, '/units')
api.add_resource(UnitResource, '/units/<int:obj_id>')

# 注册 response 文档
api.models[unit_model.name] = unit_model
